package com.zx.Ding.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zx.Ding.common.R;
import com.zx.Ding.entity.Category;
import com.zx.Ding.entity.CategoryDetail;
import com.zx.Ding.service.CategoryDetailService;
import com.zx.Ding.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private CategoryDetailService categoryDetailService;

    @GetMapping("/page")
    public R<Page> Page(int page, int pageSize){
        log.info("page={},pageSize={}",page,pageSize);
        //分页构造器
        Page pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getType);
        queryWrapper.orderByAsc(Category::getSort);
        //分页查询
        categoryService.page(pageInfo,queryWrapper);
        return R.success(pageInfo);
    }
    @PostMapping
    public R<String>save(@RequestBody Category category){
        log.info(category.toString());
        categoryService.save(category);
        //给门店详情表赋值
        CategoryDetail categoryDetail = new CategoryDetail();
        categoryDetail.setCategoryId(category.getId());
        categoryDetail.setCategoryName(category.getName());
        categoryDetail.setScore(BigDecimal.valueOf(0));
        categoryDetailService.save(categoryDetail);
        return R.success("添加成功");
    }

    //根据ID进行删除
    @DeleteMapping
    public R<String> delete(Long id){
        log.info("删除分类，id为：{}",id);
        categoryService.remove(id);
        return R.success("分类信息删除成功");
    }
    @PutMapping
    public R<String>update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    @GetMapping("/list")
    public R<List<Category>>list(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getType);
        queryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        List<Category> list = categoryService.list(queryWrapper);
        System.out.println(list);
        return R.success(list);
    }

}
